package com.yys.onmyoji.controller;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import com.yys.onmyoji.config.IdentifyCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/code")
@Api(tags = "验证码")
public class CodeController {
    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation("验证码的图片大小设置")
    @GetMapping()
    public ModelAndView createCode(HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 自定义宽、高、字数和干扰线的条数
        IdentifyCode code = new IdentifyCode(90, 30, 4, 10);
        // 存入session
        HttpSession session = request.getSession();
        session.setAttribute("code", code.getCode());
        // 响应图片
        ServletOutputStream out = response.getOutputStream();
        code.write(out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}